package com.atguigu.flink.day04;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author Felix
 * @date 2024/8/13
 * 该案例演示了分流-侧输出流
 * 需求：按照传感器id进行分流
 */
public class Flink04_Split_SlideOutput {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        //Configuration conf = new Configuration();
        //conf.set(RestOptions.PORT,8088);
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);
        //TODO 2.从指定的网络端口读取数据并将其转换为数字流
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);

        //TODO 3.对流中数据进行类型转换
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());

        //TODO 4.分流
        //4.1 定义侧输出流标签
        OutputTag<WaterSensor> ws1Tag = new OutputTag<WaterSensor>("ws1Tag"){};
        OutputTag<WaterSensor> ws2Tag = new OutputTag<WaterSensor>("ws2Tag", Types.POJO(WaterSensor.class));
        //4.2 分流
        //注意：如果要是侧输出流，只能调用process算子对流中数据进行处理，
        // 因为只有process算子在方法中能获取到context，需要通过上下文对象操作侧输出流
        SingleOutputStreamOperator<WaterSensor> processDS = wsDS.process(
                new ProcessFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor ws, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                        String id = ws.getId();
                        if ("ws1".equals(id)) {
                            //将数据"放到"侧输出流 --- 打标签
                            ctx.output(ws1Tag, ws);
                        } else if ("ws2".equals(id)) {
                            ctx.output(ws2Tag, ws);
                        } else {
                            //将其它数据放到主流
                            out.collect(ws);
                        }
                    }
                }
        );

        //TODO 5.打印
        processDS.print("主流:");
        SideOutputDataStream<WaterSensor> ws1DS = processDS.getSideOutput(ws1Tag);
        SideOutputDataStream<WaterSensor> ws2DS = processDS.getSideOutput(ws2Tag);
        ws1DS.print("侧流1");
        ws2DS.print("侧流2");

        //TODO 6.提交作业
        env.execute();

    }
}
